//
//  FFWalletManager.m
//  LLWallet
//
//  Created by tt on 2020/9/2.
//

#import "FFWalletManager.h"
#import <WuKongBase/WuKongBase.h>
#import "FFWalletVM.h"
#import "FFPayPwdUpdateVC.h"
#import "FFWalletRechargeVC.h"
static FFWalletManager *_instance = nil;

@interface FFWalletManager ()

@property(nonatomic,strong) FFWalletVM *walletVM;

@end

@implementation FFWalletManager


+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone ];
    });
    return _instance;
}

- (FFWalletVM *)walletVM {
    if(!_walletVM) {
        _walletVM = [[FFWalletVM alloc] init];
    }
    return _walletVM;
}

+(instancetype) shared{
    if (_instance == nil) {
        _instance = [[super alloc]init];
    }
    return _instance;
}

-(void) showPayPwdAndGetPayToken:(NSString*)remark title:(NSString*)title amount:(NSInteger)amount callback:(void (^)(NSString * _Nonnull))callback cancel:(void (^)(void))cancel {
        __weak typeof(self) weakSelf = self;
    NSString *titleStr = [NSString stringWithFormat:@"¥%@",[WKMoneyUtil penny2YuanFormat:@(amount)]];
    UIFont *font = [[WKApp shared].config appFontOfSizeSemibold:36.0f];
    if(title && ![title isEqualToString:@""]) {
        titleStr = title;
        font = [[WKApp shared].config appFontOfSize:16.0f];
    }
    [weakSelf showPayPwdInputDialog:remark title:titleStr titleFont:font callback:^(NSString *pwd) {
            
            [weakSelf requestGetPayToken:pwd item:@"" amount:amount callback:callback cancel:cancel];
            
        } cancel:cancel];
}


-(void) showPayPwdAndGetPayToken:(NSString*)remark amount:(NSInteger)amount callback:(void (^)(NSString * _Nonnull))callback cancel:(void (^)(void))cancel {
    [self showPayPwdAndGetPayToken:remark title:nil amount:amount callback:callback cancel:cancel];
}

-(AnyPromise*) requestPayToken:(NSString*)pwd item:(LIMPayItem)item amount:(NSInteger)amount {
   return  [[WKAPIClient sharedClient] POST:@"impay/wallet/pay/token" parameters:@{@"password":pwd?:@"",@"item":[self getPayItemStr:item],@"amount":@(amount)}];
}

-(void) requestGetPayToken:(NSString*)pwd item:(NSString*)item amount:(NSInteger)amount callback:(void (^)(NSString * _Nonnull))callback cancel:(void (^)(void))cancel{
    __weak typeof(self) weakSelf = self;
    // 从服务器获取payToken
    [[WKAPIClient sharedClient] POST:@"impay/wallet/pay/token" parameters:@{@"password":pwd?:@"",@"item":item?:@"",@"amount":@(amount)}].then(^(NSDictionary*dict){
        NSString *payToken = dict[@"pay_token"];
        if(callback) {
            callback(payToken);
        }
    }).catch(^(NSError *error){
         NSDictionary *userInfo = error.userInfo;
        if(userInfo && [userInfo[@"status"] integerValue] == 99) {
            [weakSelf showAlertForgetPayPwd];
        }else {
            [[WKNavigationManager shared].topViewController.view showHUDWithHide:error.domain];
        }
        if(cancel) {
            cancel();
        }
         
    });
}

-(void) ff_getPayToken:(NSString*)title remark:(NSString*)remark item:(LIMPayItem)item  callback:(void(^)(NSString *payToken))callback {
    [self ff_getPayToken:0 item:item title:nil remark:remark callback:callback cancel:nil];
}

- (void)ff_getPayToken:(NSInteger)amount item:(LIMPayItem)item remark:(NSString *)remark callback:(void (^)(NSString * _Nonnull))callback {
    [self ff_getPayToken:amount item:item remark:remark callback:callback cancel:nil];
}

- (void)ff_getPayToken:(NSInteger)amount item:(LIMPayItem)item remark:(NSString *)remark callback:(void (^)(NSString * _Nonnull))callback cancel:(void (^)(void))cancel {
    [self ff_getPayToken:amount item:item title:nil remark:remark callback:callback cancel:cancel];
}

-(NSString*) getPayItemStr:(LIMPayItem)item {
    switch (item) {
        case LIMPayItemRedpacket:
            return  @"redpacket";
        case LIMPayItemTransfer:
            return @"transfer";
        default:
            return @"";
    }
    return @"";
}

- (void)ff_getPayToken:(NSInteger)amount item:(LIMPayItem)item title:(NSString*)title remark:(NSString *)remark callback:(void (^)(NSString * _Nonnull))callback cancel:(void (^)(void))cancel {
    // 获取我的钱包信息
    __weak typeof(self) weakSelf = self;
    [self.walletVM myWallet:^(NSError * _Nonnull error) {
        if(error) {
            [[WKNavigationManager shared].topViewController.view showHUDWithHide:error.domain];
            if(cancel) {
                cancel();
            }
            return;
        }
        
        if(!weakSelf.walletVM.walletInfo.passwordIsSet) { // 如果没有设置付款密码，则提示去设置密码
            [self showAlertSetPayPwd];
            if(cancel) {
                cancel();
            }
            return;
            
        }else {
            if(amount>weakSelf.walletVM.walletInfo.amount) { // // 如果设置了付款密码，则判断余额是否足够，如果不足够提示去充值，如果足够则弹出输入密码提示框，如果密码输入成功，则去服务器兑换payToken
                [weakSelf showAlertRecharge];
                if(cancel) {
                    cancel();
                }
                return;
            }
            NSString *titleStr;
            NSString *itemDesc = [self getPayItemStr:item];
            BOOL needCheckFreePWD = false; // 是否需要检查免密付款
            switch (item) {
                case LIMPayItemRedpacket:
                    needCheckFreePWD = true;
                    break;
                case LIMPayItemTransfer:
                    needCheckFreePWD =  true;
                    break;
                case LIMPayItemFreePWDRedpacket:
                    titleStr = LLang(@"开启红包免密支付");
                    break;
                case LIMPayItemFreePWDTransfer:
                    titleStr = LLang(@"开启转账免密支付");
                    break;
                case LIMPayItemFreePWDPayQRCodeOn:
                    titleStr = LLang(@"开启付款码支付");
                    break;

                default:
                    if(title && ![title isEqualToString:@""]) {
                        titleStr = title;
                    }
                    break;
            }
            
            if(needCheckFreePWD) {
                [self.walletVM ff_needEnterPayPassword:itemDesc callback:^(BOOL needPayPassword, NSError * _Nonnull error) {
                    if(error) {
                        [[WKNavigationManager shared].topViewController.view showMsg:error.domain];
                        return;
                    }
                    if(needPayPassword) {
                        [self showPayPwdAndGetPayToken:remark amount:amount callback:callback cancel:cancel];
                    }else{
                        [weakSelf requestGetPayToken:@"" item:itemDesc amount:amount callback:callback cancel:cancel];
                    }
                }];
                return;
            }
            
            [self showPayPwdAndGetPayToken:remark title:titleStr amount:amount callback:callback cancel:cancel];
            
        }
        
    }];
}



// 显示设置支付密码的alert
-(void) showAlertSetPayPwd {
    [WKAlertUtil alert:LLang(@"你还未设置支付密码，是否立刻设置") buttonsStatement:@[LLang(@"否"),LLang(@"是")] chooseBlock:^(NSInteger buttonIdx) {
        if(buttonIdx == 1) {
            [[WKNavigationManager shared] pushViewController:[FFPayPwdUpdateVC new] animated:YES];
        }
    }];
}

// 显示忘记支付密码的alert
-(void) showAlertForgetPayPwd {
    [WKAlertUtil alert:LLang(@"是否忘记支付密码？") buttonsStatement:@[LLang(@"否"),LLang(@"是")] chooseBlock:^(NSInteger buttonIdx) {
        if(buttonIdx == 1) {
            [[WKNavigationManager shared] pushViewController:[FFPayPwdUpdateVC new] animated:YES];
        }
    }];
}



// 显示充值的alert
-(void) showAlertRecharge {
    [WKAlertUtil alert:LLang(@"余额不足，是否去充值") buttonsStatement:@[LLang(@"否"),LLang(@"是")] chooseBlock:^(NSInteger buttonIdx) {
        if(buttonIdx == 1) {
            [[WKNavigationManager shared] pushViewController:[FFWalletRechargeVC new] animated:YES];
        }
    }];
}

// 显示密码的dialog
-(void) showPayPwdInputDialog:(NSString*)remark title:(NSString*)title titleFont:(UIFont*)titleFont callback:(void(^)(NSString *pwd))callback cancel:(void(^)(void)) cancel{
    WKPwdKeyboardInputView *vw = [WKPwdKeyboardInputView new];
    vw.remark = remark;
    vw.title = title;
    vw.titleFont = titleFont;
    [vw setFinishBlock:^(NSString * _Nonnull pwd) {
        if(callback) {
            callback(pwd);
        }
    }];
    vw.cancelBlock = ^{
        if(cancel) {
            cancel();
        }
    };
    [vw show];
}
@end
